package com.example.server;

import com.example.coder.JSONSerializer;
import com.example.coder.RpcDecoder;
import com.example.handler.RpcHandler;
import com.example.request.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class RpcServer implements ApplicationContextAware {

    private String host;
    private int port;
    private ApplicationContext applicationContext;


    public RpcServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 启动 RpcServer
     */
    public void start() {
        System.out.println("starting rpc server......");
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        // handler 无法共享，每次新的连接，需要重新创建
                        pipeline.addLast(new RpcHandler(applicationContext));

                    }
                });
        try {
            bootstrap.bind(host,port).sync();
            System.out.println("rpc server bind on " + host + ":" + port);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
